using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Flower : MonoBehaviour
{
    public GameObject HurtNumber;
    private Renderer render;
    public int health;
    public float interval;
    public float bulletNum;
    public GameObject bulletPrefab;
    private float timer1;
    private Vector2 direction;
    private Animator anim;
    private Collider2D coll;
    private int HurtNum;
    public bool stillAlive = true;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
        coll = GetComponent<Collider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (timer1 > 0)
        {
            timer1 -= Time.deltaTime;
        }
        else 
        {
            timer1 = 0;
        }
        if (timer1 == 0 && stillAlive)
        {
            fire();
            timer1 = interval;
        }
        if (health < 0)
        {
            //GameObject.FindWithTag("Player").GetComponent<PlayerCon>().parameterPlayer.killNum++;
            stillAlive = false;
            coll.enabled = false;
            anim.Play("Death");
            coll.GetComponent<SpriteRenderer>().sortingOrder--;
        }
    }
    void fire()
    {
        anim.Play("Shoot");
        for(int i=1;i<= bulletNum; i++)
        {
            float a = Random.Range(-100, 100);
            float b = Random.Range(-100, 100);
            direction = new Vector2(a, b).normalized;
            GameObject bullet = ObjectPool.Instance.GetObject(bulletPrefab);
            bullet.transform.position = direction * Mathf.Abs(a) / 50;
            bullet.transform.position += transform.position;
            bullet.transform.right = direction;
            bullet.GetComponent<bullet>().SetSpeed(direction);
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Bullet_Player") || collision.gameObject.layer == LayerMask.NameToLayer("Knife"))
        {
            if (collision.GetComponent<bullet>() != null)
            { HurtNum = collision.GetComponent<bullet>().damage; }
            if (collision.GetComponent<bullet2>() != null)
            { HurtNum = collision.GetComponent<bullet2>().damage; }
            Vector3 vector = new Vector2((float)UnityEngine.Random.Range(-20, 20) / 100, (float)UnityEngine.Random.Range(100, 140) / 100);
            GameObject gb = Instantiate(HurtNumber, transform.position + vector, transform.rotation);
            gb.GetComponent<TextMesh>().text = HurtNum.ToString();
            health -= HurtNum;
            render.material.color = Color.red;
            Invoke("ReColor", 0.05f);
        }
    }
    void ReColor()
    {
        render.material.color = Color.white;
    }
}
